﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NLog;
using SealManagement.Common;
using SealManagement.Extensions;
using SealManagement.Models;
using SealManagement.SqlData;

namespace SealManagement.Controllers
{
    [Authorize(Roles = "SignMaker")]
    public class ProduceSignController : Controller
    {
        private SignContext _context;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public ProduceSignController(SignContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            var guid = Guid.NewGuid();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return View();
        }

        /// <summary>
        /// 制章
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            //返回当前制章人序列号用于验证
            var signMakerId = User.FindFirst(ClaimTypes.Sid).Value;
            var makerArrayNo = _context.SignMakers.Find(Convert.ToInt32(signMakerId)).ArrayNo;
            ViewData["makerArrayNo"] = makerArrayNo;
            var guid = Guid.NewGuid();
            ViewData["ValidateCode"] = guid.ToString();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return View();
        }
        /// <summary>
        /// 制章
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create(string EncryptData)
        {
            if (!Define.IsChecked)
            {
                return Json(new { state = resultType.Error, message = "系统未经自检，请先执行自检后操作" });
            }
            var jsonBack = ToolClass.EncryptTransit(EncryptData);
            //if (string.IsNullOrEmpty(jsonBack))
            //{
            //    return Json(new { state = resultType.Error, message = "参数错误" });
            //}
            if (int.TryParse(jsonBack, out var errorCodeValue))
            {
                var errorCode = (ErrorCode)errorCodeValue;
                return Json(new { state = resultType.Error, message = $"错误码：{errorCodeValue}，错误信息：{ToolClass.GetDescription(errorCode)}" });
            }
            var produceSignViewModel = JsonConvert.DeserializeObject<ProduceSignViewModel>(jsonBack);
            if (produceSignViewModel == null)
            {
                return Json(new { state = resultType.Error, message = "数据不存在" });
            }
            #region cookie验证
            var guidStr = "";
            if (!HttpContext.Request.Cookies.TryGetValue("ValidateCode", out guidStr))
            {
                return Json(new { state = resultType.Error, message = "cookie未设置，请联系管理员" });
            }
            var guidFromCookie = Encoding.UTF8.GetString(ToolClass.Decrypt(Convert.FromBase64String(guidStr)));
            if (!string.Equals(guidFromCookie, produceSignViewModel.ValidateCode, StringComparison.OrdinalIgnoreCase))
            {
                return Json(new { state = resultType.Error, message = "cookie不正确，请刷新页面后重试" });
            }
            #endregion
            //验证制章人证书
            var produceSignModel = produceSignViewModel.ProduceSign;
            var makerArrayNo = produceSignModel.MakerCertSN;
            var signmaker = await _context.SignMakers.FirstOrDefaultAsync(p => p.ArrayNo == makerArrayNo);
            if (signmaker == null)
            {
                return Json(new { state = resultType.Error, message = "不存在该制章人" });
            }

            //制章
            var produceSign = new ProduceSign()
            {
                MakerCertSN = produceSignModel.MakerCertSN,
                MakerCertBase64 = produceSignModel.MakerCertBase64,
                UserCertSN = produceSignModel.UserCertSN,
                UserCertBase64 = produceSignModel.UserCertBase64,
                CreateTime = DateTime.Now.ToString(),
                SealType = produceSignModel.SealType,
                SealBase64 = produceSignModel.SealBase64,
                SealName = produceSignModel.SealName,
                StartTime = produceSignModel.StartTime,
                EndTime = produceSignModel.EndTime
            };
            _context.Add(produceSign);
            int res = await _context.SaveChangesAsync();
            if (res > 0)
            {
                logger.Info($"制章人{User.Identity.Name}制作了签章");
                _context.InfoLogs.Add(new InfoLog()
                {
                    UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                    UserName = User.Identity.Name ?? "",
                    CreateDate = DateTime.Now.ToString(),
                    UserType = (int)userType.SignMaker,
                    Remark = $"制章人{User.Identity.Name ?? ""}制作了签章",
                    ManageType = manageType.MakeSign.ToString()
                });
            }
            _context.SaveChanges();
            return Json(new { state = resultType.Success, message = "成功制作签章" });
        }

        /// <summary>
        /// 验章
        /// </summary>
        /// <returns></returns>
        public IActionResult Verify()
        {
            var guid = Guid.NewGuid();
            ViewData["ValidateCode"] = guid.ToString();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return View();
        }
        /// <summary>
        /// 验章
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Verify(string EncryptData)
        {
            if (!Define.IsChecked)
            {
                return Json(new { state = resultType.Error, message = "系统未经自检，请先执行自检后操作" });
            }
            var jsonBack = ToolClass.EncryptTransit(EncryptData);
            //if (string.IsNullOrEmpty(jsonBack))
            //{
            //    return Json(new { state = resultType.Error, message = "参数错误" });
            //}
            if (int.TryParse(jsonBack, out var errorCodeValue))
            {
                var errorCode = (ErrorCode)errorCodeValue;
                return Json(new { state = resultType.Error, message = $"错误码：{errorCodeValue}，错误信息：{ToolClass.GetDescription(errorCode)}" });
            }
            var editStrModel = JsonConvert.DeserializeObject<EditStrModel>(jsonBack);
            if (editStrModel == null)
            {
                return Json(new { state = resultType.Error, message = "数据不存在" });
            }
            #region cookie验证
            var guidStr = "";
            if (!HttpContext.Request.Cookies.TryGetValue("ValidateCode", out guidStr))
            {
                return Json(new { state = resultType.Error, message = "cookie未设置，请联系管理员" });
            }
            var guidFromCookie = Encoding.UTF8.GetString(ToolClass.Decrypt(Convert.FromBase64String(guidStr)));
            if (!string.Equals(guidFromCookie, editStrModel.ValidateCode, StringComparison.OrdinalIgnoreCase))
            {
                return Json(new { state = resultType.Error, message = "cookie不正确，请刷新页面后重试" });
            }
            #endregion
            logger.Info($"制章人{User.Identity.Name}验证了签章");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name ?? "",
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)userType.SignMaker,
                Remark = $"制章人{User.Identity.Name ?? ""}验证了签章{editStrModel.ArrayNo}",
                ManageType = manageType.VerifySign.ToString()
            });
            await _context.SaveChangesAsync();
            return Json(new { state = resultType.Success, message = "成功验证了签章" });
        }

        /// <summary>
        /// 恢复印章
        /// </summary>
        /// <returns></returns>
        public IActionResult Restore()
        {
            var guid = Guid.NewGuid();
            ViewData["ValidateCode"] = guid.ToString();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return View();
        }

        /// <summary>
        /// 恢复印章
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public async Task<IActionResult> Restore()
        //{
        //    return Ok();
        //}
        public async Task<IActionResult> GetRestoreSeal(string EncryptData)
        {
            if (!Define.IsChecked)
            {
                return Json(new { state = resultType.Error, message = "系统未经自检，请先执行自检后操作" });
            }
            var jsonBack = ToolClass.EncryptTransit(EncryptData);
            //if (string.IsNullOrEmpty(jsonBack))
            //{
            //    return Json(new { state = resultType.Error, message = "参数错误" });
            //}
            if (int.TryParse(jsonBack, out var errorCodeValue))
            {
                var errorCode = (ErrorCode)errorCodeValue;
                return Json(new { state = resultType.Error, message = $"错误码：{errorCodeValue}，错误信息：{ToolClass.GetDescription(errorCode)}" });
            }
            var editStrModel = JsonConvert.DeserializeObject<EditStrModel>(jsonBack);
            if (editStrModel == null)
            {
                return Json(new { state = resultType.Error, message = "数据不存在" });
            }
            #region cookie验证
            var guidStr = "";
            if (!HttpContext.Request.Cookies.TryGetValue("ValidateCode", out guidStr))
            {
                return Json(new { state = resultType.Error, message = "cookie未设置，请联系管理员" });
            }
            var guidFromCookie = Encoding.UTF8.GetString(ToolClass.Decrypt(Convert.FromBase64String(guidStr)));
            if (!string.Equals(guidFromCookie, editStrModel.ValidateCode, StringComparison.OrdinalIgnoreCase))
            {
                return Json(new { state = resultType.Error, message = "cookie不正确，请刷新页面后重试" });
            }
            #endregion
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name ?? "",
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)userType.SignMaker,
                Remark = $"制章人{User.Identity.Name ?? ""}恢复了印章{editStrModel.ArrayNo}",
                ManageType = manageType.RecoverSign.ToString()
            });
            await _context.SaveChangesAsync();
            return Ok(await _context.ProduceSigns.Where(s => s.UserCertSN == editStrModel.ArrayNo).Select(s => s.SealBase64)
                .FirstOrDefaultAsync());
            //return Json(new {
            //    state = resultType.Success,
            //    message = "恢复印章成功",
            //    data = await _context.ProduceSigns.Where(s => s.UserCertSN == editStrModel.ArrayNo).Select(s => s.SealBase64)
            //    .FirstOrDefaultAsync()
        //});
        }
    }
}